<?php if (!defined('BASEPATH')) exit('No direct script access allowed');


class Users extends CI_Model
{

	private $session_name = 'admin';
	private $admin;
	
	function __construct()
	{
		parent::__construct();
	}
	
	function admin_login($admin_id){
		if ((!$admin = $this->get_admin($admin_id))) {
    		return FALSE;
    	}
    	$this->admin = $admin;
    	return TRUE;
	}

	function logged_in () {
    	if ($this->session->userdata($this->session_name) && $this->get_admin($this->session->userdata($this->session_name))) {
    		return true;
    	}
    	else {
    		return false;
    	}
    }
    
	function gen_password($length = 5)
	{
		$this->load->helper('string');
		$makepass = random_string('numeric',$length);
		return $makepass;
	}
	function has_password($password){
		return md5($password.setting('encryption_key'));
	}

	function login($username,$password){
		$username = addslashes($username);
		$password = addslashes($password);
		$password = $this->has_password($password);
		$this->db->where('username',$username);
		$this->db->where('password',$password);
		$result = $this->db->get('users');
		if ($result->num_rows() > 0) {
			$admin_db = $result->row_array();
            if($admin_db['status']!=0)
            {
    			$this->session->set_userdata($this->session_name,$admin_db['id']);
    			return true;
            }
            return false;
		}else {
			return false;
		}
		return false;
	}
	
	function logout(){
		$this->session->unset_userdata($this->session_name);
		return true;
	}
	
	function get($parameter = false){
		if ($parameter){
			return $this->admin[$parameter];
		}else{
			return $this->admin;
		}
	}
	
	
	
	function get_admin($admin_id){
		$admin_user = $this->get_admins(array('id'=>$admin_id));
		if ($admin_user){
			return $admin_user;
		}	
		return false;
	}
	
	function get_admins($filters = array(),$counting = false){
		$this->db->from('Users');
		if (isset($filters['id'])){
			$this->db->where('id',$filters['id']);
		}
		if (isset($filters['username'])){
			$this->db->where('username',$filters['username']);
		}
		$result = $this->db->get();
		
		if ($counting){
			$rows = $result->num_rows();
			$result->free_result();
			return $rows;
		}
		
		if ($result->num_rows() == 0) {
			return false;
		}
		$admin_user = array();
		$admin_user = $result->result_array();
		
		$result->free_result();
		return $admin_user;
	}
	function get_count($filters = array()){
		return $this->get_admins($filters,true);
	}
}